package pl.edu.agh.gameserv.server;

import java.util.ArrayList;

import pl.edu.agh.gameserv.gameproviderapi.GameLogic;
import pl.edu.agh.gameserv.serverapi.GameNotReadyException;
import pl.edu.agh.gameserv.serverapi.IllegalMoveException;
import pl.edu.agh.gameserv.serverapi.NotMyMoveException;

public class GameContainer {
	GameLogic game;
	String type;
	ArrayList<GameHandleImpl> handles;
	int nextMove;
	ArrayList<String> moves;

	public GameContainer(GameLogic game, String type, ArrayList<GameHandleImpl> handles) {
		this.game = game;
		this.type = type;
		this.handles = handles;

		this.moves = new ArrayList<String>();
		nextMove = 0;
		for (int i = 0; i < handles.size(); i++)
			handles.get(i).setGame(this, i);
	}

	public int nextMove() {
		return nextMove;
	}

	public String getScore() {
		return game.getScore();
	}

	public int getUserCount() {
		return handles.size();
	}

	String getUserName(int number) {
		return handles.get(number).getUserName();
	}

	Boolean isFinished() {
		return game.isFinished();
	}

	String[][] getSituation() {
		return game.getSituation();
	}

	synchronized void makeMove(GameHandleImpl handle, String move) throws GameNotReadyException, NotMyMoveException, IllegalMoveException {
		if (game.isFinished())
			throw new GameNotReadyException();

		if (nextMove != handle.getMyNumber())
			throw new NotMyMoveException();

		try {
			game.makeMove(nextMove, move);
		} catch (pl.edu.agh.gameserv.gameproviderapi.IllegalMoveException ex) {
			throw new IllegalMoveException();
		}
	//	moves.add(move);

		nextMove++;
		if (nextMove >= getUserCount())
			nextMove = 0;
	}

	/*
	 * Save game in persistent storage (if available)
	 */
	void SaveGame() {
	/*	ServiceReference<HistoryService> sr = context.getServiceReference(HistoryService.class);
		if (sr != null) {
			HistoryService hs = context.getService(sr);

			Game historicGame = new Game();
			// User user1 = hs.GetUser(handle1.getUserName());
			// User user2 = hs.GetUser(handle2.getUserName());
			// historicGame.setUser1(user1);
			// historicGame.setUser2(user2);
			historicGame.setScore(game.getScore());
			historicGame.setType(type);

			ArrayList<User> historicUsers = new ArrayList<User>();
			for (int i = 0; i < handles.size(); i++)
				historicUsers.add(hs.GetUser(getUserName(i)));

			int number = 1;
			int userNumber = 0;
			for (String[] move : moves) {
				String moveText = move[0];
				for (int i = 1; i < move.length; i++)
					moveText += ", " + move[i];

				Move historicMove = new Move();
				historicMove.setGame(historicGame);
				historicMove.setNumber(number);
				historicMove.setMove(moveText);
				historicMove.setUser(historicUsers.get(userNumber));

				userNumber++;
				if (userNumber >= getUserCount())
					userNumber = 0;
				number++;
			}
			hs.SaveGame(historicGame);

			context.ungetService(sr);
		}*/

	}

}
